import React, { useState, useEffect } from "react";
import {
  Card,
  Form,
  Input,
  Button,
  Checkbox,
  Typography,
  Space,
  Modal,
  message,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  PhoneOutlined,
  UserAddOutlined,
  KeyOutlined,
} from "@ant-design/icons";
import { useAuth } from "../contexts/AuthContext";
import { useTheme } from "../contexts/ThemeContext";
import RegisterModal from "../components/RegisterModal";
import type { LoginForm } from "../types/user";

const { Title, Text } = Typography;

interface ResetPasswordForm {
  account: string;
  phone: string;
  newPassword: string;
  confirmPassword: string;
}

const Auth: React.FC = () => {
  const { login, loading } = useAuth();
  const { theme } = useTheme();
  const [loginForm] = Form.useForm();
  const [resetForm] = Form.useForm();
  const [showRegisterModal, setShowRegisterModal] = useState(false);
  const [showResetModal, setShowResetModal] = useState(false);
  const [resetLoading, setResetLoading] = useState(false);
  const [ripples, setRipples] = useState<
    Array<{ id: number; x: number; y: number }>
  >([]);

  // 控制body滚动
  useEffect(() => {
    const hasModal = showRegisterModal || showResetModal;

    if (hasModal) {
      const scrollY = window.scrollY;
      document.body.classList.add("modal-open");
      document.body.style.position = "fixed";
      document.body.style.top = `-${scrollY}px`;
      document.body.style.width = "100%";
      document.body.style.overflow = "hidden";

      const preventScroll = (e: TouchEvent) => {
        e.preventDefault();
      };

      document.addEventListener("touchmove", preventScroll, { passive: false });

      return () => {
        document.removeEventListener("touchmove", preventScroll);
      };
    } else {
      const scrollY = document.body.style.top;
      document.body.classList.remove("modal-open");
      document.body.style.position = "";
      document.body.style.top = "";
      document.body.style.width = "";
      document.body.style.overflow = "";

      if (scrollY) {
        window.scrollTo(0, parseInt(scrollY || "0") * -1);
      }
    }

    return () => {
      document.body.classList.remove("modal-open");
      document.body.style.position = "";
      document.body.style.top = "";
      document.body.style.width = "";
      document.body.style.overflow = "";
    };
  }, [showRegisterModal, showResetModal]);

  const handleLogin = async (values: LoginForm) => {
    const success = await login(values);
    if (success) {
      loginForm.resetFields();
    }
  };

  const handleResetPassword = async (values: ResetPasswordForm) => {
    setResetLoading(true);
    try {
      await new Promise((resolve) => setTimeout(resolve, 1000));

      const users = JSON.parse(localStorage.getItem("users") || "[]");
      const userIndex = users.findIndex(
        (u: { username: string; phone: string }) =>
          (u.username === values.account || u.phone === values.account) &&
          u.phone === values.phone
      );

      if (userIndex !== -1) {
        users[userIndex].password = values.newPassword;
        localStorage.setItem("users", JSON.stringify(users));
        message.success("密码重置成功！");
        resetForm.resetFields();
        setShowResetModal(false);
      } else {
        message.error("账号或手机号不匹配！");
      }
    } catch {
      message.error("重置失败，请重试！");
    } finally {
      setResetLoading(false);
    }
  };

  const handleBackgroundClick = (e: React.MouseEvent<HTMLDivElement>) => {
    // 只在点击背景时触发，不在卡片内触发
    if (e.target === e.currentTarget) {
      const rect = e.currentTarget.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      const newRipple = {
        id: Date.now(),
        x,
        y,
      };

      setRipples((prev) => [...prev, newRipple]);

      // 0.3秒后移除波纹
      setTimeout(() => {
        setRipples((prev) =>
          prev.filter((ripple) => ripple.id !== newRipple.id)
        );
      }, 300);
    }
  };

  return (
    <div className="min-h-screen relative overflow-hidden auth-container">
      {/* 静态渐变背景 */}
      <div className="absolute inset-0">
        <div
          className="absolute inset-0"
          style={{
            background: `
              radial-gradient(ellipse 50% 40% at 20% 90%, #FA9A4B 0%, rgba(250, 154, 75, 0.3) 25%, transparent 50%),
              linear-gradient(135deg, #FAECA9 0%, #FAECA9 40%, #fff 50%, #FCCC95 60%, #FA9A4B 70%, #FCCC95 75%, #FAECA9 85%, #fff 95%, #fff 100%),
              linear-gradient(45deg, rgba(250, 236, 169, 0.15) 0%, transparent 35%, rgba(255, 255, 255, 0.4) 100%)
            `,
          }}
        ></div>

        {/* 阳光光束效果 */}
        <div className="absolute inset-0 overflow-hidden">
          {/* 主光束 */}
          <div
            className="absolute sunbeam"
            style={{
              top: "-20%",
              left: "-10%",
              width: "45%",
              height: "70%",
              background:
                "linear-gradient(135deg, rgba(255, 255, 255, 0.6) 0%, rgba(255, 255, 255, 0.3) 40%, rgba(255, 255, 255, 0.1) 70%, transparent 100%)",
              transform: "rotate(25deg)",
              transformOrigin: "top left",
            }}
          ></div>

          {/* 次要光束 */}
          <div
            className="absolute sunbeam"
            style={{
              top: "-15%",
              left: "5%",
              width: "35%",
              height: "55%",
              background:
                "linear-gradient(135deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.2) 40%, rgba(255, 255, 255, 0.08) 70%, transparent 100%)",
              transform: "rotate(20deg)",
              transformOrigin: "top left",
              animationDelay: "2s",
            }}
          ></div>

          {/* 第三光束 */}
          <div
            className="absolute sunbeam"
            style={{
              top: "-25%",
              left: "-5%",
              width: "30%",
              height: "50%",
              background:
                "linear-gradient(135deg, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0.25) 40%, rgba(255, 255, 255, 0.1) 70%, transparent 100%)",
              transform: "rotate(30deg)",
              transformOrigin: "top left",
              animationDelay: "4s",
            }}
          ></div>

          {/* 细光束 */}
          <div
            className="absolute sunbeam"
            style={{
              top: "-10%",
              left: "15%",
              width: "20%",
              height: "40%",
              background:
                "linear-gradient(135deg, rgba(255, 255, 255, 0.35) 0%, rgba(255, 255, 255, 0.15) 40%, rgba(255, 255, 255, 0.05) 70%, transparent 100%)",
              transform: "rotate(15deg)",
              transformOrigin: "top left",
              animationDelay: "6s",
            }}
          ></div>

          {/* 光粒子效果 */}
          <div
            className="absolute top-1/4 left-1/5 w-3 h-3 rounded-full light-particle"
            style={{
              background: "rgba(255, 255, 255, 0.8)",
              boxShadow: "0 0 30px rgba(255, 255, 255, 0.6), 0 0 60px rgba(255, 255, 255, 0.3)",
              animationDelay: "1s",
            }}
          ></div>

          <div
            className="absolute top-1/3 left-1/4 w-2 h-2 rounded-full light-particle"
            style={{
              background: "rgba(255, 255, 255, 0.7)",
              boxShadow: "0 0 25px rgba(255, 255, 255, 0.5), 0 0 50px rgba(255, 255, 255, 0.25)",
              animationDelay: "3s",
            }}
          ></div>

          <div
            className="absolute top-2/5 left-1/6 w-1.5 h-1.5 rounded-full light-particle"
            style={{
              background: "rgba(255, 255, 255, 0.6)",
              boxShadow: "0 0 20px rgba(255, 255, 255, 0.4), 0 0 40px rgba(255, 255, 255, 0.2)",
              animationDelay: "5s",
            }}
          ></div>

          {/* 额外的光粒子 */}
          <div
            className="absolute top-1/5 left-1/8 w-2.5 h-2.5 rounded-full light-particle"
            style={{
              background: "rgba(255, 255, 255, 0.7)",
              boxShadow: "0 0 25px rgba(255, 255, 255, 0.5), 0 0 50px rgba(255, 255, 255, 0.25)",
              animationDelay: "0.5s",
            }}
          ></div>

          <div
            className="absolute top-1/6 left-1/3 w-1 h-1 rounded-full light-particle"
            style={{
              background: "rgba(255, 255, 255, 0.5)",
              boxShadow: "0 0 15px rgba(255, 255, 255, 0.4), 0 0 30px rgba(255, 255, 255, 0.2)",
              animationDelay: "7s",
            }}
          ></div>
        </div>
      </div>

      {/* 波纹效果 */}
      {ripples.map((ripple) => (
        <div
          key={ripple.id}
          className="ripple-effect"
          style={{
            left: ripple.x,
            top: ripple.y,
          }}
        />
      ))}

      {/* 主要内容区域 - 居中布局 */}
      <div
        className="relative z-10 min-h-screen flex items-center justify-center p-8"
        onClick={handleBackgroundClick}
      >
        <div className="w-full max-w-md">
          <Card
            className="shadow-2xl border-0 login-card"
            style={{
              backgroundColor: "rgba(255, 255, 255, 0.25)",
              borderRadius: "24px",
              border: "2px solid rgba(255, 255, 255, 0.8)",
              backdropFilter: "blur(20px)",
              boxShadow: `
                0 25px 50px rgba(0, 0, 0, 0.15),
                0 0 0 1px rgba(255, 255, 255, 0.6),
                inset 0 1px 0 rgba(255, 255, 255, 0.9),
                inset 0 -1px 0 rgba(0, 0, 0, 0.05)
              `,
            }}
          >
            <div className="text-center mb-6">
              <Title
                level={3}
                className="mb-2"
                style={{ color: theme.colors.primary[600] }}
              >
                欢迎回来
              </Title>
              <Text type="secondary">登录您的账号继续使用</Text>
            </div>

            <Form
              form={loginForm}
              name="login"
              onFinish={handleLogin}
              layout="vertical"
              size="large"
            >
              <Form.Item
                name="account"
                label="账号/手机号"
                rules={[{ required: true, message: "请输入账号或手机号!" }]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="请输入账号或手机号"
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: "请输入密码!" }]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                />
              </Form.Item>

              <div className="flex justify-between items-center mb-6">
                <Form.Item
                  name="remember"
                  valuePropName="checked"
                  className="mb-0"
                >
                  <Checkbox>记住我</Checkbox>
                </Form.Item>
                <Button
                  type="link"
                  className="p-0 h-auto"
                  onClick={() => setShowResetModal(true)}
                >
                  忘记密码？
                </Button>
              </div>

              <Form.Item className="mb-4">
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                  size="large"
                  style={{
                    backgroundColor: theme.colors.primary[500],
                    borderColor: theme.colors.primary[500],
                  }}
                >
                  登录
                </Button>
              </Form.Item>

              <Form.Item className="mb-0">
                <Button
                  type="default"
                  block
                  size="large"
                  icon={<UserAddOutlined />}
                  onClick={() => setShowRegisterModal(true)}
                >
                  注册新账号
                </Button>
              </Form.Item>
            </Form>
          </Card>

          <RegisterModal
            open={showRegisterModal}
            onCancel={() => setShowRegisterModal(false)}
          />

          <Modal
            title={
              <div className="text-center">
                <KeyOutlined
                  className="mr-2"
                  style={{ color: theme.colors.primary[500] }}
                />
                重置密码
              </div>
            }
            open={showResetModal}
            onCancel={() => {
              setShowResetModal(false);
              resetForm.resetFields();
            }}
            footer={null}
            width={450}
            centered
            className="reset-modal"
          >
            <Form
              form={resetForm}
              name="resetPassword"
              onFinish={handleResetPassword}
              layout="vertical"
              size="large"
            >
              <Form.Item
                name="account"
                label="账号"
                rules={[{ required: true, message: "请输入账号!" }]}
              >
                <Input prefix={<UserOutlined />} placeholder="请输入您的账号" />
              </Form.Item>

              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: "请输入手机号!" },
                  { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号!" },
                ]}
              >
                <Input
                  prefix={<PhoneOutlined />}
                  placeholder="请输入绑定的手机号"
                />
              </Form.Item>

              <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                  { required: true, message: "请输入新密码!" },
                  { min: 6, message: "密码至少6个字符!" },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入新密码"
                />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="确认新密码"
                dependencies={["newPassword"]}
                rules={[
                  { required: true, message: "请确认新密码!" },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue("newPassword") === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error("两次输入的密码不一致!"));
                    },
                  }),
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请再次输入新密码"
                />
              </Form.Item>

              <Form.Item className="mb-0">
                <Space className="w-full">
                  <Button
                    onClick={() => {
                      setShowResetModal(false);
                      resetForm.resetFields();
                    }}
                    className="flex-1"
                  >
                    取消
                  </Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={resetLoading}
                    className="flex-1"
                    style={{
                      backgroundColor: theme.colors.primary[500],
                      borderColor: theme.colors.primary[500],
                    }}
                  >
                    重置密码
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Modal>

          <div className="text-center mt-6">
            <Text className="text-white/80 text-sm">
              © 2024 管理系统. 保留所有权利.
            </Text>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Auth;
